import os
import sys
import hashlib
import sqlite3
from datetime import datetime

def calculate_file_hash(file_path):
    """计算文件的SHA256哈希值"""
    hasher = hashlib.sha256()
    with open(file_path, 'rb') as f:
        buf = f.read()
        hasher.update(buf)
    return hasher.hexdigest()

def create_db_table(conn):
    """创建表结构"""
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS video_hash (
            id INTEGER PRIMARY KEY,
            file_path TEXT NOT NULL,
            file_name TEXT NOT NULL,
            file_hash TEXT NOT NULL,
            create_time TEXT NOT NULL
        )
    ''')
    # 清空表数据
    cursor.execute('DELETE FROM video_hash')
    conn.commit()

def insert_into_db(conn, file_path, file_name, file_hash):
    """插入数据到数据库"""
    cursor = conn.cursor()
    now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    cursor.execute('''
        INSERT INTO video_hash (file_path, file_name, file_hash, create_time) VALUES (?, ?, ?, ?)
    ''', (file_path, file_name, file_hash, now))
    conn.commit()
    return now  # 返回插入时间

def scan_directory_and_store_hashes(directory, db_conn):
    """扫描目录并存储文件哈希值"""
    counter = 0
    for root, dirs, files in os.walk(directory):
        for name in files:
            file_path = os.path.join(root, name)
            relative_path = os.path.relpath(file_path, directory)
            file_hash = calculate_file_hash(file_path)
            insert_time = insert_into_db(db_conn, relative_path, name, file_hash)

            # 每处理100个文件，打印一次信息（包括序号）
            if counter % 100 == 0:
                print(f'Processing file #{counter + 1}: {name}, Time: {insert_time}')
            counter += 1

if __name__ == '__main__':
    
    if len(sys.argv) != 2:
        print("使用方法: python 00_scan_video.py <directory>")
        sys.exit(1)

    video_dir = sys.argv[1]

    db_path = os.path.join(video_dir, 'file_hash.db')

    # 创建/连接数据库
    conn = sqlite3.connect(db_path)
    
    # 创建表
    create_db_table(conn)

    # 扫描目录并存储哈希值
    scan_directory_and_store_hashes(video_dir, conn)

    # 关闭数据库连接
    conn.close()